package com.example.demo.nio;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.Callable;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

@Service
public class LocalNewsAsyncContext {
    private final static Long timeOutSeconds= 5L;
    @Autowired
    private CustomAsyncListener asyncListener;
    @Autowired
    private ThreadPoolExecutor executor;

    public void submit(final HttpServletRequest request,final Callable<Object> task){
        final String uri= request.getRequestURI();
        final Map<String,String[]> params= request.getParameterMap();
        //开启异步上下文
        final AsyncContext asyncContext= request.startAsync();
        asyncContext.getRequest().setAttribute(Constant.URI, uri);
        asyncContext.getRequest().setAttribute(Constant.PARAMS, params);
        asyncContext.setTimeout(timeOutSeconds * 1000);
        if(asyncContext!=null){
            asyncContext.addListener(asyncListener);
        }
        executor.submit(new CustomCallable(asyncContext, task));
    }
}
